package com.powerunion.datacollection.service;

import java.util.List;


import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.powerunion.datacollection.common.SystemException;
import com.powerunion.datacollection.dao.DaoFactory;
import com.powerunion.datacollection.dao.TargetFieldsDao;
import com.powerunion.datacollection.model.TargetFields;

import com.powerunion.util.log.LogHelper;

public class TargetFieldsManager {
	private static Logger logger = LogHelper.getInstance().getLogger(TargetFieldsManager.class);
	private TargetFieldsDao dao = null;
	public TargetFieldsManager() {
		super();
		this.dao = (TargetFieldsDao)DaoFactory.getInstance().getDao(TargetFieldsDao.class);
	}
	
	public boolean save(String saveStr,String categoryId) {
		//参数为空
		if(StringUtils.isEmpty(saveStr)) {
			String[] args = { "saveStr" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter saveStr NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		
		//参数为空
		if(StringUtils.isEmpty(categoryId)) {
			String[] args = { "categoryId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter categoryId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		//先删除原有的，再添加
		this.delete(categoryId);
		
		TargetFields tf = (TargetFields)JSONObject.toBean(JSONObject.fromObject(saveStr), TargetFields.class);
		String itemselector = tf.getItemselector();
		String itemselectorStr = "kernel_value,"+itemselector;
		String[] fieldNames = StringUtils.split(itemselectorStr, ",");
		
		return this.dao.save(fieldNames,categoryId);
	}
	
	public boolean delete(String categoryId) {
		//参数为空
		if(StringUtils.isEmpty(categoryId)) {
			String[] args = { "categoryId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter categoryId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		
		return this.dao.delete(categoryId);
	}
	
	public String getTargetFields(String categoryId){
		List columns = this.dao.getTargetFields(categoryId);
		JSONArray jsonArr = JSONArray.fromObject(columns);
		String result = "{results:"+jsonArr+"}";
		return result;
	}
	
}
